import pyperclip
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton, QTextEdit
from PyQt5.QtGui import QFont

class BaseConverterTab(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()

        font = QFont()
        font.setPointSize(12)  # 设置字体大小

        self.description_label = QLabel('说明: 该工具可以进行二进制、八进制、十进制和十六进制之间的转换。')
        self.description_label.setFont(font)
        layout.addWidget(self.description_label)

        self.input_label = QLabel('输入:')
        self.input_label.setFont(font)
        layout.addWidget(self.input_label)

        self.input_entry = QLineEdit(self)
        self.input_entry.setFont(font)
        self.input_entry.textChanged.connect(self.convert_base)  # 当输入框内容变化时，自动进行转换
        layout.addWidget(self.input_entry)

        self.paste_button = QPushButton('粘贴', self)
        self.paste_button.setFont(font)
        self.paste_button.clicked.connect(self.paste_text)
        layout.addWidget(self.paste_button)

        self.clear_button = QPushButton('清空', self)
        self.clear_button.setFont(font)
        self.clear_button.clicked.connect(self.clear_text)
        layout.addWidget(self.clear_button)

        self.result_label = QLabel('结果:')
        self.result_label.setFont(font)
        layout.addWidget(self.result_label)

        self.result_text = QTextEdit(self)
        self.result_text.setFont(font)
        self.result_text.setReadOnly(True)
        layout.addWidget(self.result_text)

        self.copy_button = QPushButton('复制结果', self)
        self.copy_button.setFont(font)
        self.copy_button.clicked.connect(self.copy_result)
        layout.addWidget(self.copy_button)

        self.setLayout(layout)

    def paste_text(self):
        self.input_entry.setText(pyperclip.paste())

    def convert_base(self):
        input_text = self.input_entry.text()
        try:
            if input_text.startswith('0b'):
                num = int(input_text, 2)
            elif input_text.startswith('0o'):
                num = int(input_text, 8)
            elif input_text.startswith('0x'):
                num = int(input_text, 16)
            else:
                num = int(input_text, 10)

            bin_result = bin(num)
            oct_result = oct(num)
            dec_result = str(num)
            hex_result = hex(num)

            result = f"二进制: {bin_result}\n八进制: {oct_result}\n十进制: {dec_result}\n十六进制: {hex_result}"
            self.result_text.setText(result)
        except ValueError:
            self.result_text.setText("输入无效，请输入有效的数字。")

    def copy_result(self):
        pyperclip.copy(self.result_text.toPlainText())

    def clear_text(self):
        self.input_entry.clear()
        self.result_text.clear()